package com.fxz.mvcframework.servlet;

import com.fxz.mvcframework.annotations.FxzAutowired;
import com.fxz.mvcframework.annotations.FxzController;
import com.fxz.mvcframework.annotations.FxzRequestMapping;
import com.fxz.mvcframework.annotations.FxzService;
import com.fxz.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-20 12:02
 */
public class FxzDispatcherServlet extends HttpServlet {

    /**
     * 配置文件信息
     */
    private Properties properties = new Properties();

    /**
     * 缓存扫描到的类的全限定类名
     */
    private List<String> classNames = new ArrayList<String>();

    /**
     * ioc容器
     */
    private Map<String, Object> ioc = new HashMap<String, Object>();

    /**
     * 存储url和method之间的映射关系
     */
    //private Map<String, Method> handlerMapping = new HashMap<String, Method>();
    private List<Handler> handlerMapping = new ArrayList<Handler>();

    /**
     * 初始化
     *
     * @param config
     */
    @Override
    public void init(ServletConfig config) {
        //1.加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2.扫描相关的类 扫描注解
        doScan(properties.getProperty("scanPackage"));


        //3.初始化bean对象(实现ioc容器 基于注解)
        try {
            doInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //4.实现依赖注入
        try {
            doAutoWired();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        //5.构造一个handlerMapping处理器映射器 将配置好的url和method建立映射关系
        initHandlerMapping();

        System.out.println("初始化完成......");
        //6.等待请求进入 处理请求
    }

    /**
     * 构造一个handlerMapping处理器映射器
     * 最关键的环节
     * 目的:将url和method建立关联
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取当前遍历对象的class类型
            Class<?> aClass = entry.getValue().getClass();

            if (!aClass.isAnnotationPresent(FxzController.class)) {
                continue;
            }

            String baseUrl = "";
            if (aClass.isAnnotationPresent(FxzRequestMapping.class)) {
                FxzRequestMapping annotation = aClass.getAnnotation(FxzRequestMapping.class);
                baseUrl = annotation.value();
            }

            //获取方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(FxzRequestMapping.class)) {
                    continue;
                }
                FxzRequestMapping annotation = method.getAnnotation(FxzRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;


                //把method所有信息以及url封装成handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                //计算方法的参数位置信息
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];

                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        //如果是request和response对象 那么参数名称存HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(), i);
                    }
                }

                //建立url和method之间的映射关系(map缓存起来)
                //handlerMapping.put(url, method);
                handlerMapping.add(handler);
            }
        }
    }

    /**
     * 实现依赖注入
     */
    private void doAutoWired() throws IllegalAccessException {
        if (ioc.isEmpty()) {
            return;
        }
        //有对象 再进行依赖注入
        //遍历ioc中的对象 查看对象中的字段 是否有@FxzAutowired注解 如果有需要维护依赖注入关系
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取bean对象中的字段信息
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            //遍历字段信息 进行处理
            for (Field field : fields) {
                if (!field.isAnnotationPresent(FxzAutowired.class)) {
                    continue;
                }
                //有FxzAutowired注解
                FxzAutowired annotation = field.getAnnotation(FxzAutowired.class);
                //需要注入的beanId
                String beanId = annotation.value();
                if ("".equals(beanId.trim())) {
                    //没有配置具体的beanId 需要根据当前字段类型注入(接口注入)
                    beanId = field.getType().getName();
                }
                //开始赋值
                field.setAccessible(true);
                field.set(entry.getValue(), ioc.get(beanId));
            }
        }
    }

    /**
     * ioc容器
     * 基于classNames缓存的类的全限定类名 以及反射技术 完成对象的创建和管理
     */
    private void doInstance() throws Exception {

        if (classNames.size() == 0) {
            return;
        }

        //实例化缓存的全限定类名到ioc容器
        for (String className : classNames) {
            //反射创建对象
            Class<?> aClass = Class.forName(className);
            //区分Controller Service
            if (aClass.isAnnotationPresent(FxzController.class)) {
                //controller的id 不做过多处理 不取value 就拿类的首字母小写作为id 保存到ioc容器
                String simpleName = lowerFirst(aClass.getSimpleName());
                Object o = aClass.newInstance();
                ioc.put(simpleName, o);
            } else if (aClass.isAnnotationPresent(FxzService.class)) {
                FxzService annotation = aClass.getAnnotation(FxzService.class);
                //获取注解value值
                String beanName = annotation.value();
                //如果没有指定 就以类名首字母小写 如果指定了id 就以指定的为准
                if ("".equals(beanName.trim())) {
                    beanName = lowerFirst(aClass.getSimpleName());
                }
                ioc.put(beanName, aClass.newInstance());

                //service曾往往是有接口的 面向接口开发 此时再以接口名为id 放入一份到ioc 便于后期根据接口类型注入
                Class<?>[] interfaces = aClass.getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    //以接口的全限定类名为id 放入ioc容器
                    ioc.put(anInterface.getName(), aClass.newInstance());
                }
            } else {
                continue;
            }
        }

    }

    /**
     * 首字母小写
     *
     * @param str DemoController
     * @return demoController
     */
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if (chars[0] >= 'A' && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * 扫描类
     *
     * @param scanPackage com.fxz.demo  package------> 磁盘上的文件夹(file)
     */
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            //子目录
            if (file.isDirectory()) {
                //递归
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                //缓存扫描扫的java类
                classNames.add(className);
            }
        }

    }

    /**
     * 加载配置文件
     *
     * @param contextConfigLocation 配置文件的路径
     */
    private void doLoadConfig(String contextConfigLocation) {
        //根据配置文件的路径 加载成流
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            //加载到properties中
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受 处理get请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 接受 处理post请求 (真正的处理请求)
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //根据uri获取到能够处理当前请求的hanlder(从handlermapping(list)中)
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        //参数绑定
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上述数组长度 创建一个新的数组(参数数组 是要传入反射调用的)
        Object[] paraValues = new Object[parameterTypes.length];
        //向参数数组设置值 保证参数的顺序和方法中形参的顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        //遍历所有请求参数
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");
            //如果参数和方法中的参数匹配上,填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }
            //方法形参中有该参数 找到他的索引 对应的把参数放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            paraValues[index] = value;
        }

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());

        if (requestIndex != null) {
            paraValues[requestIndex] = req;
        }
        if (responseIndex != null) {
            paraValues[responseIndex] = resp;
        }

        //最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }
}
